#!/bin/bash
SCRIPT_ABS_FILENAME=`LC_ALL=en_US.ISO8859-1 perl -e 'use Cwd "abs_path";print abs_path(shift)' "${BASH_SOURCE[0]}"`
SCRIPT_DIR=`dirname "$SCRIPT_ABS_FILENAME"`

#echo `pwd`
#echo BASH_SOURCE="${BASH_SOURCE[@]}"
#echo "$0" "$@"

me=`basename "$0"`   # get invocation name (not the name of the target of the link)
#echo me=$me

name="${me##*-}"
#echo name=$name

prefix=${me%-$name}
echo prefix=$prefix

mkdir -p "$SCRIPT_DIR"/DerivedData/clang-slink

#parameter 1
dsc_file="$SCRIPT_DIR"/../../CLover.dsc        # path of the dsc file
echo dsc_file=$dsc_file

#parameter 2
component=rEFIt_UEFI/refit.inf        # path to .inf under edk2 directory, see components section in dsc file. Ie RefindPkg/refind/refind.inf
echo component=$component

#parameter 3
edk2config="DEBUG_XCODE8"      # configuration name of edk2 build script (ie DEBUG_GCC49)
echo edk2config=$edk2config

#parameter 4
libname="$1"         # lib name generated by Xcode
echo libname=$libname

#parameter 5
edk2prefix="../.."            # path "$edk2prefix" to edk2 directory
echo edk2prefix=$edk2prefix


#computed variables
component_path="$(dirname "$component")/$(basename "$component" .inf)"
echo component_path=$component_path

edk2project="$("$SCRIPT_DIR"/get_unique_property PLATFORM_NAME "$dsc_file")"
echo edk2project=$edk2project

edk2libname="$("$SCRIPT_DIR"/get_unique_property BASE_NAME "$edk2prefix"/"$component").lib"
echo edk2libname="$edk2libname"

outputname="./DerivedData/clang-slink/CloverX64"           # output name
echo outputname="$outputname"




[[ -f ./"$outputname".dll ]] && rm -f ./"$outputname".dll
[[ -f ./"$outputname".pecoff ]] && rm -f ./"$outputname".pecoff
[[ -f ./"$outputname".efi ]] && rm -f ./"$outputname".efi
[[ -f ./BOOTX64.efi ]] && rm -f ./BOOTX64.efi

awk '!/'"$edk2libname"'/' "$edk2prefix"/Build/"$edk2project"/"$edk2config"/X64/"$component_path"/OUTPUT/static_library_files.lst > "$outputname"_file_list.lst

ld -arch x86_64 -u __ModuleEntryPoint  -e __ModuleEntryPoint -preload -segalign 0x20 -pie -all_load -dead_strip -seg1addr 0x240 -map "$outputname".map \
  -o ./"$outputname".dll "$libname" -filelist "$outputname"_file_list.lst "$edk2prefix"/Build/"$edk2project"/"$edk2config"/X64/"$component_path"/OUTPUT/AutoGen.obj \



source ./mtoc_path.txt
[[ $? == 0 ]] && "$MTOC" -subsystem UEFI_APPLICATION  -align 0x20 ./"$outputname".dll ./"$outputname".pecoff

[[ $? == 0 ]] && dsymutil ./"$outputname".dll

[[ $? == 0 ]] && "$edk2prefix"/BaseTools/Source/C/bin/GenFw -e UEFI_APPLICATION -o ./"$outputname".efi ./"$outputname".pecoff

[[ $? == 0 ]] && echo link successful
